package category

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	empty "github.com/golang/protobuf/ptypes/empty"
	"go.uber.org/zap"
	"mxshop-api/goods-web/api"
	"mxshop-api/goods-web/forms"
	"mxshop-api/goods-web/global"
	"mxshop-api/goods-web/global/reponse"
	"mxshop-api/goods-web/proto"
	"mxshop-api/goods-web/utils"
	"net/http"
	"strconv"
)

func List(ctx *gin.Context) {
	r, err := global.GoodsSrvClient.GetAllCategorysList(context.Background(), &empty.Empty{})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	data := make([]interface{}, 0)
	err = json.Unmarshal([]byte(r.JsonData), &data)
	if err != nil {
		zap.S().Errorw("[category-List] 查询 【分类列表】失败:", err.Error())
	}

	ctx.JSON(http.StatusOK, data)
}

func Detail(ctx *gin.Context) {
	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}

	reMap := make(map[string]interface{})
	subCategorys := make([]interface{}, 0)
	if r, err := global.GoodsSrvClient.GetSubCategory(context.Background(), &proto.CategoryListRequest{
		Id: int32(i),
	}); err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	} else {
		for _, value := range r.SubCategorys {
			subCategorys = append(subCategorys, map[string]interface{}{
				"id":              value.Id,
				"name":            value.Name,
				"level":           value.Level,
				"parent_category": value.ParentCategory,
				"is_tab":          value.IsTab,
			})
		}
		reMap["id"] = r.Info.Id
		reMap["name"] = r.Info.Name
		reMap["level"] = r.Info.Level
		reMap["parent_category"] = r.Info.ParentCategory
		reMap["is_tab"] = r.Info.IsTab
		reMap["sub_categorys"] = subCategorys

		ctx.JSON(http.StatusOK, reMap)
	}
	return
}

func New(ctx *gin.Context) {
	categoryForm := forms.CategoryForm{}
	if err := ctx.ShouldBindJSON(&categoryForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	rsp, err := global.GoodsSrvClient.CreateCategory(context.Background(), &proto.CategoryInfoRequest{
		Name:           categoryForm.Name,
		IsTab:          *categoryForm.IsTab,
		Level:          categoryForm.Level,
		ParentCategory: categoryForm.ParentCategory,
	})

	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	request := make(map[string]interface{})
	request["id"] = rsp.Id
	request["name"] = rsp.Name
	request["parent"] = rsp.ParentCategory
	request["level"] = rsp.Level
	request["is_tab"] = rsp.IsTab

	ctx.JSON(http.StatusOK, request)
}

func Delete(ctx *gin.Context) {
	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}

	// 1. 先查询出该分类下的所有子分类
	// 2. 将所有的 冷类全部逻辑删除
	// 3. 将该分类下的所有的商品逻辑删除
	_, err = global.GoodsSrvClient.DeleteCategory(context.Background(), &proto.DeleteCategoryRequest{Id: int32(i)})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.Status(http.StatusOK)
}

func Update(ctx *gin.Context) {
	categoryForm := forms.UpdateCategoryForm{}
	if err := ctx.ShouldBindJSON(&categoryForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}

	request := &proto.CategoryInfoRequest{
		Id:   int32(i),
		Name: categoryForm.Name,
	}
	if categoryForm.IsTab != nil {
		request.IsTab = *categoryForm.IsTab
	}
	_, err = global.GoodsSrvClient.UpdateCategory(context.Background(), request)
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.Status(http.StatusOK)
}

// IndexGoodsList TODO 这里应该再
func IndexGoodsList(ctx *gin.Context) {
	// 先 获取 1级类目
	//再从1级类目中 获取相关品牌(这里简单处理 选择前3个)
	//再从1级类目下 获取相关商品(这里简单处理 随机6个 和 随机一个推荐)
	result := make([]interface{}, 0)

	// 获取 获取子分类
	categoryRsp, err := global.GoodsSrvClient.GetAllCategorysList(context.Background(), &empty.Empty{})
	if err != nil {
		return
	}
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	var categoryResponse []reponse.CategoryResponse
	_ = json.Unmarshal([]byte(categoryRsp.JsonData), &categoryResponse)

	for _, category := range categoryResponse {
		reMap := make(map[string]interface{})
		var brands []interface{}
		var subCat []any
		for _, subCategory := range category.SubCat {
			subCat = append(subCat, map[string]any{
				"id":              subCategory.Id,
				"name":            subCategory.Name,
				"level":           subCategory.Level,
				"is_tab":          subCategory.IsTab,
				"parent_category": subCategory.ParentCategory,
			})

			for i := 0; i < len(subCategory.SubCat) && len(brands) < 3; i++ {
				// 获取对应的品牌信息
				rsp, err := global.GoodsSrvClient.GetCategoryBrandList(context.Background(), &proto.CategoryInfoRequest{
					Id: subCategory.SubCat[i].Id,
				})
				if err != nil {
					api.HandleGrpcErrorToHttp(err, ctx)
					return
				}
				for i := 0; i < utils.Min(int(rsp.Total), 3-len(brands)); i++ {
					brands = append(brands, map[string]any{
						"id":       rsp.Data[i].Id,
						"name":     rsp.Data[i].Name,
						"image":    rsp.Data[i].Logo,
						"category": subCategory.SubCat[i].Id,
					})
				}
			}

		}

		goods, err := global.GoodsSrvClient.GoodsList(context.Background(), &proto.GoodsFilterRequest{
			Pages:       1,
			PagePerNums: 7,
			TopCategory: category.Id,
		})
		if err != nil {
			zap.S().Errorw("[IndexGoodsList] 查询 【商品列表】 失败")
			api.HandleGrpcErrorToHttp(err, ctx)
			return
		}
		adGoods := api.ChangeToResponse(goods.Data[0])
		var lastGoods []any
		for _, good := range goods.Data[1:] {
			lastGoods = append(lastGoods, api.ChangeToResponse(good))
		}

		reMap["id"] = category.Id
		reMap["name"] = category.Name
		reMap["category_type"] = category.Level
		reMap["is_tab"] = category.IsTab
		reMap["brands"] = brands
		reMap["ad_goods"] = adGoods
		reMap["goods"] = lastGoods
		reMap["sub_cat"] = subCat
		result = append(result, reMap)
	}
	ctx.JSON(http.StatusOK, result)
}
